package edu.upb.acs.jobsmaps.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.AudioManager;
import android.os.Bundle;
import android.speech.SpeechRecognizer;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import edu.upb.acs.jobsmaps.R;
import edu.upb.acs.jobsmaps.activity.voiceRecognition.VoiceRecognitionListenerJob;
import edu.upb.acs.jobsmaps.database.task.AddJobTask;
import edu.upb.acs.jobsmaps.entity.CompanyIdentifier;
import edu.upb.acs.jobsmaps.entity.Job;
import edu.upb.acs.jobsmaps.util.Companies;
import edu.upb.acs.jobsmaps.voice.VoiceUtils;

public class AddJobActivity extends Activity implements OnInitListener {
    final Context context = this;
    private Button addButton;
    private static final String TAG = "AddJobActivity";
    private SpeechRecognizer sr;
    private Intent intent;
    private TextToSpeech tts;
    private AudioManager amAudioManager;


    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.addjob);

        // components from main.xml
        addButton = (Button) findViewById(R.id.AddJobButtonAdd);

        // add button listener
        addButton.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {
                createJob();

                AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
                        context);
                alertDialogBuilder.setMessage("Job was added with success");
                alertDialogBuilder.setCancelable(false).setPositiveButton("OK",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                // when the ok button is pushed, return to main
                                // view
                                setResult(RESULT_OK);
                                finish();
                            }
                        }
                );

                // create alert dialog
                AlertDialog alertDialog = alertDialogBuilder.create();
                // show it
                alertDialog.show();
            }
        });
        Companies.populateSpinnerCompanies((Spinner) findViewById(R.id.editJobCompany), this);

        Button goBackButton = (Button) findViewById(R.id.AddJobButtonCancel);
        goBackButton.setOnClickListener(new OnClickListener() {
            public void onClick(View arg0) {
                goToMainActivity();
            }
        });

        //continue with voice recognition

        //the audio manager for microphone
        amAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

        //create a new speaker
        tts = new TextToSpeech(this, this);

        Log.d(TAG, "Entering startListening");
        startListening();
    }

    @Override
    public void onStart() {
        super.onStart();
        Log.d(TAG, "In the onStart() event");

    }

    @Override
    public void onDestroy() {
        if (tts != null) {
            tts.stop();
            tts.shutdown();
        }

        sr.stopListening();
        sr.destroy();
        super.onDestroy();
    }

    private void startListening() {
        sr = SpeechRecognizer.createSpeechRecognizer(this);

        intent = VoiceUtils.initializeIndent(intent, getApplicationContext());

        sr.setRecognitionListener(new VoiceRecognitionListenerJob(sr, intent, tts, amAudioManager, this));
        sr.startListening(intent);
    }


    @Override
    public void onInit(int status) {
        if (status == TextToSpeech.SUCCESS) {
            //Speak
            tts.speak("Enter name", TextToSpeech.QUEUE_FLUSH, null);
            while (tts.isSpeaking()) {
                //Log.d(TAG, "She is speaking");
            }
        } else {
            //Handle initialization error here
            Log.d(TAG, "Initialization for TTS failed!!!");
        }
    }

    private void createJob() {
        final Job job = new Job();

        final EditText nameField = (EditText) findViewById(R.id.EditJobName);
        String name = nameField.getText().toString();
        System.out.println("job name = >" + name + "<");
        job.setName(name);

        final EditText descField = (EditText) findViewById(R.id.EditJobDescription);
        String description = descField.getText().toString();
        System.out.println("job description = >" + description + "<");
        job.setDescription(description);

        Spinner spinner = (Spinner) findViewById(R.id.editJobCompany);
        CompanyIdentifier value = (CompanyIdentifier) spinner.getSelectedItem();
        job.setCompanyId(String.valueOf(value.getId()));

        Double latitude = Double.valueOf(((EditText) findViewById(R.id.editJobLatitude)).getText().toString());
        job.setLatitude(latitude);

        Double longitude = Double.valueOf(((EditText) findViewById(R.id.editJobLongitude)).getText().toString());
        job.setLongitude(longitude);

        final EditText salaryField = (EditText) findViewById(R.id.editJobSalary);
        String salary = salaryField.getText().toString();
        System.out.println("job salary = >" + salary + "<");
        //TODO error handling: salary it's not a valid number
        if (salary != null && salary.length() > 0) {
            job.setSalary(Integer.valueOf(salary));
        }

        final EditText jobUrlField = (EditText) findViewById(R.id.editJobUrl);
        String jobUrl = jobUrlField.getText().toString();
        System.out.println("job url = >" + jobUrl + "<");
        job.setJobUrl(jobUrl);

//        final EditText jobDateField = (EditText) findViewById(R.id.editJobPostedDate);
//        String jobDate = jobDateField.getText().toString();
//        System.out.println("job date = >" + jobDate + "<");
//        job.setPostedDate(new Date(Date.parse(jobDate)));

        job.setActive(true);

        AddJobTask addJobTask = new AddJobTask();
        try {
            Integer persistedJobId = addJobTask.execute(job).get();
            Log.d(TAG, "New job id = " + persistedJobId);
        } catch (Exception e) {
            Log.e(TAG, "Can not persist job", e);
        }
    }

    private void goToMainActivity() {
        setResult(RESULT_OK);
        finish();
    }
}
